package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.DrugType;
import me.xue.communityhealth.service.DrugTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DrugTypeController {

    private final DrugTypeService service;

    @Autowired
    public DrugTypeController(DrugTypeService service) {
        this.service = service;
    }

    @GetMapping("/drugTypes")
    public String all(Model model) {
        List<DrugType> drugTypes = service.findAll();
        model.addAttribute("drugTypes", drugTypes);
        return "drug_types";
    }

    @GetMapping("/drugType/add")
    public String addPage(Model model) {
        model.addAttribute("drugType", new DrugType());
        return "drug_type_edit";
    }

    @PostMapping("/drugType")
    public String add(DrugType drugType) {
        if (service.save(drugType) == 1) {
            return "redirect:/drugTypes";
        }
        return "drug_type_edit";
    }

    @DeleteMapping("/drugType/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        if (service.delete(id) == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/drugType/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        DrugType drugType = service.findOne(id);
        model.addAttribute("drugType", drugType);
        return "drug_type_edit";
    }

    @PutMapping("/drugType")
    public String update(DrugType drugType) {
        if (service.update(drugType) == 1) {
            return "redirect:/drugTypes";
        }
        return "drug_type_edit";
    }
    
}
